import { connect } from 'umi';
import { Modal, Form } from 'antd';
import ProForm, { ProFormText, ProFormDigit, ProFormTextArea } from '@ant-design/pro-form';
import {SystemAreaTreeSelect} from '@/components/system/area'
import {SystemDeptTreeSelect} from '@/components/system/dept'

const SystemDeptForm = (props) => {
  const {
    SystemDeptModel: { formVisible, formType, dept },
    dispatch,
  } = props;

  const [form] = Form.useForm();

  const onCancel = () => {
    dispatch({ type: 'SystemDeptModel/changeFormVisibleReducer', payload: false });
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...dept, ...fieldsValue };

    if (formType === 'raise') {
      await dispatch({ type: 'SystemDeptModel/saveEffect', payload: formValue });
    }
    
    if (formType === 'modify') {
      await dispatch({ type: 'SystemDeptModel/updateEffect', payload: formValue });
    }

    dispatch({ type: 'SystemDeptModel/listTreeEffect' });
    onCancel();
  }

  return (
    <Modal
      destroyOnClose
      title={formType === 'raise' ? '新增部门信息' : '修改部门信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={dept} form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <Form.Item label="所属区域" name="areaId" >
          <SystemAreaTreeSelect/>
        </Form.Item>
        <Form.Item label="上级部门" name="parentId" >
          <SystemDeptTreeSelect disabledKey={dept.id}/>
        </Form.Item>
        <ProFormText  name="code" label="部门编码" rules={[{ required: true, message: '请输入部门编码!' }, {max: 20, message: '部门编码过长!'}]}/>
        <ProFormText  name="name" label="部门名称" rules={[{ required: true, message: '请输入部门名称!' }, {max: 20, message: '部门名称过长!'}]}/>
        <ProFormText  name="simpleName" label="部门简称" rules={[{ required: true, message: '请输入部门简称!' }, {max: 20, message: '部门简称过长!'}]}/>
        <ProFormDigit label="部门排序" name="sort" min={1} max={10000} rules={[{ required: true, message: '请输入部门排序!' }]}/>
        <ProFormTextArea  label="备注说明" name="remark" rules={[ {max: 100, message: '备注过长!'}]}/>
      </ProForm>
    </Modal>
  );
};

export default connect(({ SystemDeptModel }) => ({
  SystemDeptModel
}))(SystemDeptForm);
